package copyengine.resource.file
{
	import copyengine.resource.dto.ResInitDTO;
	import copyengine.utils.GeneralUtils;
	import copyengine.utils.CEStringUtils;
	import copyengine.utils.debug.CELog;

	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.text.Font;

	public class CEFontResourceFile extends CEBasicResFile
	{

		/**
		 * an loader use to load  the swf file
		 */
		private var swfLoader:Loader;

		private var resFilePath:String;

		public function CEFontResourceFile()
		{
			super();
		}

		override protected function doInitialize(_resInitDTO:ResInitDTO):void
		{
			resFilePath = _resInitDTO.filePath;
		}

		override protected function doStartLoadFile():void
		{
			swfLoader = new Loader();
			swfLoader.load(new URLRequest(resFilePath));
			GeneralUtils.addTargetEventListener(swfLoader.contentLoaderInfo, Event.COMPLETE, onLoaded);
			GeneralUtils.addTargetEventListener(swfLoader.contentLoaderInfo, ProgressEvent.PROGRESS, loadFileOnProgress);
			GeneralUtils.addTargetEventListener(swfLoader.contentLoaderInfo, IOErrorEvent.IO_ERROR, loadFileOnError,false,0,true);
		}

		override protected function releaseLoader():void
		{
			if (swfLoader != null)
			{
				swfLoader.unloadAndStop(true);
				GeneralUtils.removeTargetEventListener(swfLoader.contentLoaderInfo, Event.COMPLETE, onLoaded);
				GeneralUtils.removeTargetEventListener(swfLoader.contentLoaderInfo, ProgressEvent.PROGRESS, loadFileOnProgress);
				GeneralUtils.removeTargetEventListener(swfLoader.contentLoaderInfo, IOErrorEvent.IO_ERROR, loadFileOnError);
			}
			swfLoader = null;
		}

		private function onLoaded(e:Event):void
		{
			var loaderInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			var domain:ApplicationDomain = loaderInfo.applicationDomain;
			try
			{
				var FontClass:Class = domain.getDefinition(CEStringUtils.remove(resFileName, ".swf") + "_FontClass") as Class;
				Font.registerFont(FontClass);
			}
			catch (err:Error)
			{
				CELog.err("FontResouce Name :" + fileName + "  must use FontClass as the font embed class name");
			}
			//FontResouce must hold swfLoader , can not dispose it.
			loadFileComplate();
		}
	}
}